/*
 * @Author: gonglf
 * @Date: 2022-08-22 15:27:00
 * @LastEditors: gonglf
 * @LastEditTime: 2022-08-22 15:59:04
 * @Description:
 *
 */
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"time"

	"gitee.com/network-learning/rpc/5gRPC_stream/pb"
	"google.golang.org/grpc"
)

/*
1、双向流数据的发送和接收都是完全独立的行为

*/

func main() {
	conn, err := grpc.Dial("localhost:1234", grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	client := pb.NewHelloServiceClient(conn)
	reply, err := client.Hello(context.Background(), &pb.String{Value: "龚凌锋"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(reply.GetValue())

	stream, err := client.Channel(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	go func() { //发送操作
		for {
			if err := stream.Send(&pb.String{Value: "hi"}); err != nil {
				log.Fatal(err)
			}
			time.Sleep(time.Second)
		}
	}()

	for { //接收操作
		reply, err := stream.Recv()
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Fatal(err)
		}
		fmt.Println(reply.GetValue())
	}
}
